//
//  NSString+MLXEXtension.m
//  MLX
//
//  Created by SY on 2018/9/25.
//  Copyright © 2018年 SY. All rights reserved.
//

#import "NSString+MLXEXtension.h"

#import <CommonCrypto/CommonCrypto.h>
@implementation NSString (MLXEXtension)
/**
 *  URLEncode
 */
- (NSString *)URLEncodedString
{
    // CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
    // CharactersToLeaveUnescaped = @"[].";
    
    NSString *unencodedString = self;
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}

/**
 *  URLDecode
 */
-(NSString *)URLDecodedString
{
    //NSString *decodedString = [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
    
    NSString *encodedString = self;
    NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                     (__bridge CFStringRef)encodedString,
                                                                                                                     CFSTR(""),
                                                                                                                     CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}
/** 删除所有的空格 */
-(NSString *)deleteSpace{
    
    NSMutableString *strM = [NSMutableString stringWithString:self];
    
    [strM replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:NSMakeRange(0, strM.length)];
    
    return [strM copy];
}
+(NSString *)fileMD5WithAsset:(NSData *)data
{
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(data.bytes, (CC_LONG)[data length], result);
    return  [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ];
    
}
+ (NSString *)md5:(NSString *)string{
    const char *cStr = [string UTF8String];
    unsigned char result[16]= "0123456789abcdef";
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

+(NSString *)getTimesTemp{
    return  [NSString stringWithFormat:@"%.0lf", [[NSDate date] timeIntervalSince1970] *1000];
}


+(BOOL)isPriceNumber:(UITextField *)textField range:(NSRange)range replacementString:(NSString *)string{
    //    限制只能输入数字
    BOOL isHaveDian = YES;
    
    if ([textField.text rangeOfString:@"."].location == NSNotFound) {
        isHaveDian = NO;
    }
    
    if ([string length] > 0) {
        
        unichar single = [string characterAtIndex:0];//当前输入的字符
        if ((single >= '0' && single <= '9') || single == '.') {//数据格式正确
            
            if([textField.text length] == 0){
                if(single == '.') {
                    NSLog(@"数据格式有误");
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            
            //输入的字符是否是小数点
            if (single == '.') {
                if(!isHaveDian)//text中还没有小数点
                {
                    isHaveDian = YES;
                    return YES;
                    
                }else{
                    NSLog(@"数据格式有误");
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }else{
                if (isHaveDian) {//存在小数点
                    
                    //判断小数点的位数
                    NSRange ran = [textField.text rangeOfString:@"."];
                    if (range.location - ran.location <= 2) {
                        return YES;
                    }else{
                        NSLog(@"最多两位小数");
                        return NO;
                    }
                }else{
                    return YES;
                }
            }
        }else{//输入的数据格式不正确
            NSLog(@"数据格式有误");
            [textField.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
        }
    }
    else
    {
        return YES;
    }
}
//验证身份证
//必须满足以下规则
//1. 长度必须是18位，前17位必须是数字，第十八位可以是数字或X
//2. 前两位必须是以下情形中的一种：11,12,13,14,15,21,22,23,31,32,33,34,35,36,37,41,42,43,44,45,46,50,51,52,53,54,61,62,63,64,65,71,81,82,91
//3. 第7到第14位出生年月日。第7到第10位为出生年份；11到12位表示月份，范围为01-12；13到14位为合法的日期
//4. 第17位表示性别，双数表示女，单数表示男
//5. 第18位为前17位的校验位
//算法如下：
//（1）校验和 = (n1 + n11) * 7 + (n2 + n12) * 9 + (n3 + n13) * 10 + (n4 + n14) * 5 + (n5 + n15) * 8 + (n6 + n16) * 4 + (n7 + n17) * 2 + n8 + n9 * 6 + n10 * 3，其中n数值，表示第几位的数字
//（2）余数 ＝ 校验和 % 11
//（3）如果余数为0，校验位应为1，余数为1到10校验位应为字符串“0X98765432”(不包括分号)的第余数位的值（比如余数等于3，校验位应为9）
//6. 出生年份的前两位必须是19或20
+ (BOOL)verifyIDCardNumber:(NSString*)value
{
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([value length] != 18) {
        return NO;
    }
    NSString* mmdd = @"(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8])))";
    NSString* leapMmdd = @"0229";
    NSString* year = @"(19|20)[0-9]{2}";
    NSString* leapYear = @"(19|20)(0[48]|[2468][048]|[13579][26])";
    NSString* yearMmdd = [NSString stringWithFormat:@"%@%@", year, mmdd];
    NSString* leapyearMmdd = [NSString stringWithFormat:@"%@%@", leapYear, leapMmdd];
    NSString* yyyyMmdd = [NSString stringWithFormat:@"((%@)|(%@)|(%@))", yearMmdd, leapyearMmdd, @"20000229"];
    NSString* area = @"(1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5]|82|[7-9]1)[0-9]{4}";
    NSString* regex = [NSString stringWithFormat:@"%@%@%@", area, yyyyMmdd, @"[0-9]{3}[0-9Xx]"];
    
    NSPredicate* regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if (![regexTest evaluateWithObject:value]) {
        return NO;
    }
    int summary = ([value substringWithRange:NSMakeRange(0, 1)].intValue + [value substringWithRange:NSMakeRange(10, 1)].intValue) * 7
    + ([value substringWithRange:NSMakeRange(1, 1)].intValue + [value substringWithRange:NSMakeRange(11, 1)].intValue) * 9
    + ([value substringWithRange:NSMakeRange(2, 1)].intValue + [value substringWithRange:NSMakeRange(12, 1)].intValue) * 10
    + ([value substringWithRange:NSMakeRange(3, 1)].intValue + [value substringWithRange:NSMakeRange(13, 1)].intValue) * 5
    + ([value substringWithRange:NSMakeRange(4, 1)].intValue + [value substringWithRange:NSMakeRange(14, 1)].intValue) * 8
    + ([value substringWithRange:NSMakeRange(5, 1)].intValue + [value substringWithRange:NSMakeRange(15, 1)].intValue) * 4
    + ([value substringWithRange:NSMakeRange(6, 1)].intValue + [value substringWithRange:NSMakeRange(16, 1)].intValue) * 2
    + [value substringWithRange:NSMakeRange(7, 1)].intValue * 1 + [value substringWithRange:NSMakeRange(8, 1)].intValue * 6
    + [value substringWithRange:NSMakeRange(9, 1)].intValue * 3;
    NSInteger remainder = summary % 11;
    NSString* checkBit = @"";
    NSString* checkString = @"10X98765432";
    checkBit = [checkString substringWithRange:NSMakeRange(remainder, 1)]; // 判断校验位
    return [checkBit isEqualToString:[[value substringWithRange:NSMakeRange(17, 1)] uppercaseString]];
}

//银行卡
+ (BOOL)validateBankCardNumber:(NSString*)bankCardNumber
{
    BOOL flag;
    if (bankCardNumber.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString* regex2 = @"^(\\d{15,18})";
    NSPredicate* bankCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex2];
    return [bankCardPredicate evaluateWithObject:bankCardNumber];
}
+ (BOOL) checkCardNo:(NSString*) cardNo {
    int oddsum = 0;     //奇数求和
    int evensum = 0;    //偶数求和
    int allsum = 0;
    int cardNoLength = (int)[cardNo length];
    int lastNum = [[cardNo substringFromIndex:cardNoLength-1] intValue];
    
    cardNo = [cardNo substringToIndex:cardNoLength - 1];
    for (int i = cardNoLength -1 ; i>=1;i--) {
        NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1, 1)];
        int tmpVal = [tmpString intValue];//卡的倒数位数值
        if (cardNoLength % 2 ==1 ) {//卡的长度是奇数
            if((i % 2) == 0){//卡的倒数第二位开始 index是否是偶数
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }else{
            if((i % 2) == 1){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }
    }
    
    allsum = oddsum + evensum;
    allsum += lastNum;
    if((allsum % 10) == 0)
        return YES;
    else
        return NO;
}
//用户名
+ (BOOL)validateUserName:(NSString*)name
{
    NSString* userNameRegex = @"^[A-Za-z0-9]{4,20}+$";
    NSPredicate* userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:name];
    return B;
}
//密码
+ (BOOL)validatePassword:(NSString*)passWord
{
    NSString* passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
    NSPredicate* passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}
//验证中文汉字字母
+ (BOOL)validateString:(NSString*)regStr
{
    NSString* userNameRegex = @"^[a-zA-Z\u4e00-\u9fa5]+$";
    NSPredicate* userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:regStr];
    return B;
}
//图片名称
+ (NSString*)imageNameWithCurrentDate
{
    
    NSDate* date = [NSDate date];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* comps = [calendar components:( kCFCalendarUnitYear | kCFCalendarUnitMonth | kCFCalendarUnitDay | kCFCalendarUnitHour | kCFCalendarUnitMinute | kCFCalendarUnitSecond)fromDate:date];
    NSInteger year = [comps year];
    NSInteger month = [comps month];
    NSInteger day = [comps day];
    NSInteger hour = [comps hour];
    NSInteger minute = [comps minute];
    NSInteger second = [comps second];
    NSString* str = [NSString stringWithFormat:@"%ld%ld%ld%ld%ld%ld.jpg", (long)year, (long)month, (long)day, (long)hour, (long)minute, (long)second];
    return str;
}
+ (BOOL)isMobileNumber:(NSString*)mobileNum
{
    if (mobileNum.length != 11)
    {
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[0, 1, 6, 7, 8], 18[0-9]
     * 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
     * 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
     * 电信号段: 133,149,153,170,173,177,180,181,189
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
     */
    NSString *CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[08]|8[2-478])\\d{8}$";
    /**
     * 中国联通：China Unicom
     * 130,131,132,145,155,156,170,171,175,176,185,186
     */
    NSString *CU = @"^1(3[0-2]|4[5]|5[56]|7[0156]|8[56])\\d{8}$";
    /**
     * 中国电信：China Telecom
     * 133,149,153,170,173,177,180,181,189,199
     */
    NSString *CT = @"^1(3[3]|4[9]|53|7[037]|8[019]|9[9])\\d{8}$";
    
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
+ (BOOL)CheckInput:(NSString*)text
{
    if (text.length < 6) {
        return NO;
    }else{
        
        return YES;
    }
}

+ (BOOL)judgeOnlyIncludeCENOrComma:(NSString *)str regexStr:(NSString *)regexStr{
    NSString * regex = regexStr;
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:str];
}
+ (BOOL)hasChinese:(NSString *)str{
    
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
    }
    return NO;
}
+ (BOOL)judgeOnlyIncludeCEN:(NSString *)str
{
    NSString * regex = @"[a-zA-Z0-9\u3400-\u9fff]+";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:str];
}
/**
 *  判断字符串中是否只有
 */
+ (BOOL)isChinese:(NSString *)str{
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:str];
}

+ (BOOL)isEnglishWordOrNumber:(NSString *)str{
    
    NSString* userNameRegex = @"^[A-Za-z0-9]+$";
    NSPredicate* userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:str];
    return B;
}

+ (BOOL)isOnlyNumber:(NSString *)str{
    
    NSString* userNameRegex = @"^[0-9]+$";
    NSPredicate* userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:str];
    return B;
}

+ (BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}


//手机号码验证
+ (BOOL)validateMobile:(NSString*)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString* phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate* phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}



/*
 *  时间戳对应的NSDate
 */
-(NSDate *)date{
    
    NSTimeInterval timeInterval=self.floatValue;
    
    return [NSDate dateWithTimeIntervalSince1970:timeInterval];
}


/**
 *  时间戳转格式化的时间字符串
 */
-(NSString *)timestampToTimeStringWithFormatString:(NSString *)formatString{
    //时间戳转date
    NSDate *date=[NSDate dateWithTimeIntervalSince1970:[self integerValue]];
    
    return [self timeStringFromDate:date formatString:formatString];
}

-(NSString *)timeStringFromDate:(NSDate *)date formatString:(NSString *)formatString{
    //实例化时间格式化工具
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    
    //定义格式
    formatter.dateFormat=formatString;
    
    //时间转化为字符串
    NSString *dateString = [formatter stringFromDate:date];
    
    return dateString;
}

- (CGSize)sizeWithMaxSize:(CGSize)maxSize andFont:(UIFont *)font
{
    //  maxSize 文字可绘制最大区域
    //  NSStringDrawingUsesLineFragmentOrigin 只有这个家伙是支持多行文本的
    //  attributes中的NSFontAttributeName 这个key对应 计算时文字的字体（UIFont）
    //  context:绘制这个字符串的上下文对象，如果是nil，就是只当前的上下文，一般情况都是nil
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;
}

/**
 *  在密文中抽取正确的密文和密钥
 */
- (NSArray *)takeRightCiphertextAndKey{
    
    NSString *rightText = @"";
    NSString *key = @"";
    for (NSInteger i = 0; i < self.length; i++) {
        if (i != 0 && i % 3 == 0 && key.length<8) {
            //            int  b= [[a substringWithRange:NSMakeRange(4,2)] intValue];
            key = [NSString stringWithFormat:@"%@%@",key,[self substringWithRange:NSMakeRange(i,1)]];
        }else{
            rightText = [NSString stringWithFormat:@"%@%@",rightText,[self substringWithRange:NSMakeRange(i,1)]];
        }
    }
    NSArray *arr = [NSArray arrayWithObjects:rightText,key, nil];
    //    NSLog(@"rightText------%@",rightText);
    //    NSLog(@"key------------%@",key);
    return arr;
}

//判定是否为邮箱地址
+(BOOL)isEmail:(NSString *)email{
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
    
    return [emailTest evaluateWithObject:email];
    
}

//判断是否全为空格
+ (BOOL)isEmptyStr:(NSString *) str {
    
    if (!str) {
        return true;
    } else {
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}

//是否浮点
+(BOOL)isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}

+ (NSInteger)genderOfIDNumber:(NSString *)IDNumber
{
    //  记录校验结果：0未知，1男，2女
    NSInteger result = 0;
    NSString *fontNumer = nil;
    
    if (IDNumber.length == 15)
    { // 15位身份证号码：第15位代表性别，奇数为男，偶数为女。
        fontNumer = [IDNumber substringWithRange:NSMakeRange(14, 1)];
        
    }else if (IDNumber.length == 18)
    { // 18位身份证号码：第17位代表性别，奇数为男，偶数为女。
        fontNumer = [IDNumber substringWithRange:NSMakeRange(16, 1)];
    }else
    { //  不是15位也不是18位，则不是正常的身份证号码，直接返回
        return result;
    }
    
    NSInteger genderNumber = [fontNumer integerValue];
    
    if(genderNumber % 2 == 1)
        result = 1;
    
    else if (genderNumber % 2 == 0)
        result = 2;
    return result;
}
- (NSString *)addParameters:(NSDictionary *)parameters {
    NSMutableArray *parts = [NSMutableArray array];
    
    for (NSString *key in [parameters allKeys]) {
        NSString *part = [NSString stringWithFormat:@"%@=%@", key, [parameters valueForKey:key]];
        [parts addObject: part];
    }
    
    NSString *parametersString= [parts componentsJoinedByString:@"&"];
    
    NSString *addSuffixString = @"";
    if ([[self parseURLParameters] count] > 0) {
        addSuffixString = [NSString stringWithFormat:@"%@%@", @"&", parametersString]; // 原链接已经存在参数, 则用"&"直接拼接参数;
    } else {
        addSuffixString = [NSString stringWithFormat:@"%@%@", @"?", parametersString]; // 原链接不存在参数, 则先添加"?", 再拼接参数;
    }
    
    return [self stringByAppendingString:addSuffixString];
}

- (NSString *)deleteParameterOfKey:(NSString *)key; {
    NSString *finalString = [NSString string];
    
    if ([self containsString:key]) {
        NSMutableString *mutStr = [NSMutableString stringWithString:self];
        NSArray *strArray = [mutStr componentsSeparatedByString:key];
        
        NSMutableString *firstStr = [strArray objectAtIndex:0];
        NSMutableString *lastStr = [strArray lastObject];
        
        NSRange characterRange = [lastStr rangeOfString:@"&"];
        
        if (characterRange.location != NSNotFound) {
            NSArray *lastArray = [lastStr componentsSeparatedByString:@"&"];
            NSMutableArray *mutArray = [NSMutableArray arrayWithArray:lastArray];
            [mutArray removeObjectAtIndex:0];
            
            NSString *modifiedStr = [mutArray componentsJoinedByString:@"&"];
            finalString = [[strArray objectAtIndex:0]stringByAppendingString:modifiedStr];
        } else {
            finalString = [firstStr substringToIndex:[firstStr length] - 1];
        }
    } else {
        finalString = self;
    }
    
    return finalString;
}

- (NSString *)modifyParameterOfKey:(NSString *)key toValue:(NSString *)toValue {
    NSDictionary *parameters = [self parseURLParameters];
    
    if (parameters.count > 0 && [parameters.allKeys containsObject:key]) {
        [parameters setValue:toValue forKey:key];
    }
    
    NSString *urlString = self;
    for (NSString *key in parameters.allKeys) {
        urlString =    [urlString deleteParameterOfKey:key];
    }
    
    return [urlString addParameters:parameters];
}

- (NSMutableDictionary *)parseURLParameters {
    NSRange range = [self rangeOfString:@"?"];
    if (range.location == NSNotFound) return nil;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    NSString *parametersString = [self substringFromIndex:range.location + 1];
    if ([parametersString containsString:@"&"]) {
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [parameters valueForKey:key];
            if (existValue != nil) {
                if ([existValue isKindOfClass:[NSArray class]]) {
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    [parameters setValue:items forKey:key];
                } else {
                    [parameters setValue:@[existValue, value] forKey:key];
                }
            } else {
                [parameters setValue:value forKey:key];
            }
        }
    } else {
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        if (pairComponents.count == 1) {
            return nil;
        }
        
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        if (key == nil || value == nil) {
            return nil;
        }
        [parameters setValue:value forKey:key];
    }
    
    return parameters;
}
+ (BOOL)isUrlAddress:(NSString*)url{
    NSString*reg =@"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    NSPredicate*urlPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg];
    return[urlPredicate evaluateWithObject:url];
    
}
+ (BOOL)isSocialCredit18Number:(NSString *)socialCreditNum{
    if(socialCreditNum.length != 18){
        return NO;
    }
    
//    NSString *scN = @"^([0-9ABCDEFGHJKLMNPQRTUWXY]{2})([0-9]{6})([0-9ABCDEFGHJKLMNPQRTUWXY]{9})([0-9Y])$";
//    NSPredicate *regextestSCNum = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", scN];
//    if (![regextestSCNum evaluateWithObject:socialCreditNum]) {
//        return NO;
//    }
    
    NSArray *ws = @[@1,@3,@9,@27,@19,@26,@16,@17,@20,@29,@25,@13,@8,@24,@10,@30,@28];
    NSDictionary *zmDic = @{@"A":@10,@"B":@11,@"C":@12,@"D":@13,@"E":@14,@"F":@15,@"G":@16,@"H":@17,@"J":@18,@"K":@19,@"L":@20,@"M":@21,@"N":@22,@"P":@23,@"Q":@24,@"R":@25,@"T":@26,@"U":@27,@"W":@28,@"X":@29,@"Y":@30};
    NSMutableArray *codeArr = [NSMutableArray array];
    NSMutableArray *codeArr2 = [NSMutableArray array];
    
    codeArr[0] = [socialCreditNum substringWithRange:NSMakeRange(0,socialCreditNum.length-1)];
    codeArr[1] = [socialCreditNum substringWithRange:NSMakeRange(socialCreditNum.length-1,1)];
    
    int sum = 0;
    
    for (int i = 0; i < [codeArr[0] length]; i++) {
        
        [codeArr2 addObject:[codeArr[0] substringWithRange:NSMakeRange(i, 1)]];
    }
    
    NSScanner* scan;
    int val;
    for (int j = 0; j < codeArr2.count; j++) {
        scan = [NSScanner scannerWithString:codeArr2[j]];
        if (![scan scanInt:&val] && ![scan isAtEnd]) {
            codeArr2[j] = zmDic[codeArr2[j]];
        }
    }
    
    
    for (int x = 0; x < codeArr2.count; x++) {
        sum += [ws[x] intValue]*[codeArr2[x] intValue];
    }
    
    
    int c18 = 31 - (sum % 31);
    
    for (NSString *key in zmDic.allKeys) {
        
        if (zmDic[key]==[NSNumber numberWithInt:c18]) {
            if (![codeArr[1] isEqualToString:key]) {
                return NO;
            }
        }
    }
    
    return YES;
}

//汉字转化成字母
- (NSString *)convertChinese{
    if(!self.length){return @"#";}
    
    NSString *first = (self.length == 1) ? self : [self substringToIndex:1];
    
    //查看是否是特殊字符
    NSString *special = [first identifySpecialWord];
    if(special){return special;}
    
    //查看是否是属于多音字范畴
    NSString *complex = [self complexChinese];
    if(complex){return complex;}
    
    //就是普通汉字了
    NSMutableString *mut = [first mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)mut, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)mut, NULL, kCFStringTransformStripCombiningMarks, NO);
    
    return mut ? [[mut substringToIndex:1] uppercaseString] : @"#";
}

/*
 多音字单独处理；
 用作姓氏的汉字一共大概五千来个；
 其中是多音字，且做姓氏时的声母与不做姓氏时声明还不同的，大概就十几个；
 目前下面收录的已经足够满足需求了。
 如果将来开发者有发现新的不在下面方法里的，请补充。
 */
- (NSString *)complexChinese{
    if([self isEqualToString:@"曾"]){return @"Z";}
    if([self isEqualToString:@"翟"]){return @"Z";}
    if([self isEqualToString:@"覃"]){return @"Q";}
    if([self isEqualToString:@"尉"]){return @"Y";}
    if([self isEqualToString:@"仇"]){return @"Q";}
    if([self isEqualToString:@"长"]){return @"Z";}
    if([self isEqualToString:@"单"]){return @"S";}
    if([self isEqualToString:@"解"]){return @"X";}
    if([self isEqualToString:@"隗"]){return @"K";}
    if([self isEqualToString:@"查"]){return @"Z";}
    return nil;
}

//特殊符号，返回#
- (NSString *)identifySpecialWord{
    unichar index = [self characterAtIndex:0];
    
    if(index >= 'a' && index <= 'z'){return self.uppercaseString;}
    if(index >= 'A' && index <= 'Z'){return self;}
    if(index <= 0x4e00 || index >= 0x9fff){return @"#";}
    
    return nil;
}
- (NSString *)deleteSpaceCharacter{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
-(NSArray *)jsonWithArray{
    if (!self.length) return @[];
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *arr  = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    if ([arr isKindOfClass:NSArray.class]) {
        return arr;
    }else{
        return @[];
    }
}
@end
